<script>
  import * as echarts from "echarts";
  import { onMount, onDestroy } from "svelte";
  import { useChartData } from "../utils/useChartData.js";

  export let endpoint = "";
  export let title = "";
  export let polling = 0; // milliseconds
  export let authToken = "";
  export let unit = "";
  export let data = null;

  let container;
  let chart;

  // Use shared data fetching logic
  const { loading, error, fetchData, cleanup } = useChartData();

  function renderChart(payload) {
    if (!chart) return;

    const series = (payload.series ?? []).map((item) => ({
      type: item.type ?? payload.type ?? "line",
      name: item.name,
      data: item.data ?? [],
      smooth: item.smooth ?? true,
      showSymbol: item.showSymbol ?? false,
      areaStyle: item.areaStyle,
      emphasis: item.emphasis
    }));

    const option = {
      title: {
        text: payload.title ?? title
      },
      tooltip: {
        trigger: "axis"
      },
      legend: {
        data: payload.legend ?? series.map((s) => s.name).filter(Boolean)
      },
      grid: {
        left: "3%",
        right: "3%",
        bottom: "10%",
        containLabel: true
      },
      xAxis: payload.xAxis ?? { type: "time" },
      yAxis: payload.yAxis ?? {
        type: "value",
        name: payload.unit ?? unit
      },
      series
    };

    chart.setOption(option, true);
  }

  function resizeHandler() {
    chart?.resize();
  }

  onMount(() => {
    chart = echarts.init(container);

    // Render provided data immediately
    if (data) {
      renderChart(data);
      loading.set(false);
    }
    // Otherwise fetch from endpoint
    else if (endpoint) {
      fetchData(endpoint, authToken, polling, renderChart);
    }

    window.addEventListener("resize", resizeHandler);
  });

  onDestroy(() => {
    cleanup();
    window.removeEventListener("resize", resizeHandler);
    chart?.dispose();
  });
</script>

<div class="chart" bind:this={container}></div>
{#if $loading}
  <p class="status">Loading data...</p>
{:else if $error}
  <p class="status error">{$error}</p>
{/if}

<style>
  .chart {
    width: 100%;
    min-height: 320px;
  }
  .status {
    margin-top: 0.5rem;
    font-size: 0.875rem;
    color: var(--muted-color, #555);
  }
  .status.error {
    color: #c0392b;
  }
</style>
